<?php
//-------------------------------------------------------------------------
// OVIDENTIA http://www.ovidentia.org
// Ovidentia is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2, or (at your option)
// any later version.
// 
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
// See the GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//-------------------------------------------------------------------------
/**
 * @license http://opensource.org/licenses/gpl-license.php GNU General Public License (GPL)
 * @copyright Copyright (c) 2006 by CANTICO ({@link http://www.cantico.fr})
 */
include_once 'base.php';
require_once $GLOBALS['babInstallPath'] . '/addons/widgets/widgets/suggestlineedit.class.php';


/**
 * Constructs a Widget_TimePicker.
 *
 * @param string		$id			The item unique id.
 * @return Widget_TimePicker
 */
function Widget_TimePicker($id = null)
{
	return new Widget_TimePicker($id);
}


/**
 * A Widget_TimePicker is a widget that let the user enter a time. 
 */
class Widget_TimePicker extends Widget_SuggestLineEdit implements Widget_Displayable_Interface
{

	/**
	 * @param string $id			The item unique id.
	 */
	public function __construct($id = null)
	{
		parent::__construct($id);
		
		$this->setMinChars(0);
		$this->setSize(5);
		$this->setMaxSize(5);

		if (false !== $keyword = $this->getSearchKeyword()) {

			$hm = explode(':', $keyword);
			for ($h = 0; $h < 24; $h++) {
				if ($hm[0] != '' && $hm[0] != $h) {
					continue;
				}
				for ($m = 0; $m < 60; $m += 30) {
					$time = sprintf('%02d:%02d', $h, $m);
					$this->addSuggestion($time, $time);
				}
			}
			$this->addSuggestion('', '');
			
			for ($h = 0; $h < 24; $h++) {
				if ($hm[0] != '' && $hm[0] != $h) {
					for ($m = 0; $m < 60; $m += 30) {
						$time = sprintf('%02d:%02d', $h, $m);
						$this->addSuggestion($time, $time);
					}
				}
			}

			$this->sendSuggestions();
		}
	}

	

	/**
	 * Sets the format of the date.
	 * Only usage of %H and %i are allowed
	 *
	 * @param string $format	The format string as described in the php strftime function.
	 */
	public function setFormat($format)
	{
		assert('is_string($format); /* The "format" parameter must be a string */');
		$this->setMetadata('format', $format);
		return $this;
	}

	/**
	 * Returns the format of the time.
	 *
	 * @return string
	 */
	public function getFormat()
	{
		return $this->getMetadata('format');
	}


	/**
	 * @return string 	The time or empty string
	 */
	public function getValue() {
	
		$value = parent::getValue();
		if ('' === $value) {
			return '';
		}
			
		if (!preg_match('/\d\d:\d\d/', $value)) {
			if (false === $value = $this->getISOTime($value)) {
				return '';
			}
		}
		
		assert('preg_match(\'/\d\d:\d\d/\', $value); /* The "value" must be an ISO time or empty string, not (' . $value . ') */');
		
		if ($this->isDisplayMode()) {
			if(strlen($value) == 8){
				$value = substr($value, 0,5);
				$value = str_replace(':', 'h', $value);
			}
		}
		return $value;
	}


	public function getClasses()
	{
		$classes = parent::getClasses();
		$classes[] = 'widget-timepicker';
		return $classes;
	}

	
	/**
	 * get title of widget (tooltip)
	 * @return string
	 */
	public function getTitle()
	{
		$title = parent::getTitle();
//		if (!isset($title)) {
//			$timeFormat = str_replace(array('%H', '%M'), array('hh', 'mm'), $this->getFormat());
//			$timeExample = strftime($this->getFormat(), bab_mktime('2000-01-01 15:32:00'));
//			return sprintf(widget_translate("Time format: '%s'.  Eg. '%s'"), $timeFormat, $timeExample);
//		}
		return $title; 
	}
	
	
	/**
	 * get ISO from a time typed in the format set in the setFormat method
	 * @param	string	$time
	 * @return 	string|false	ISO time or false if error
	 */
	public function getISOTime($time) 
	{
		if (empty($time)) {
			return '--:--';
		}

		$expreg = str_replace(
			array('%H', '%M'), 
			array('(?P<hour>[0-9]{1,2})', '(?P<minute>[0-9]{1,2})'),
			'/'.preg_quote($this->getFormat(), '/').'/'
		);

		if (preg_match($expreg, $date, $regs)) {
			return sprintf('%02d:%02d',$regs['hour'],$regs['minute']);
		} else {
			return false;
		}
	
	}
	

}
